package redis

import (
	redisgo "github.com/gomodule/redigo/redis"
	"github.com/nitishm/go-rejson"
)

type Cmd struct {
	RunMode   string
	Conn      redisgo.Conn
	SlaveConn redisgo.Conn
}

func (r *Redis) Conn() (cmd *Cmd, err error) {

	var conn redisgo.Conn

	switch r.RunMode {
	case RunModeStandard:
		conn = r.Pool.Get()
	case RunModeSentinel:
		conn = r.SentinelPool.Get()
	case RunModeCluster:
		if err := r.ClusterPool.Refresh(); err != nil {
			return nil, err
		}

		conn = r.ClusterPool.Get()
	}

	return &Cmd{
		RunMode: r.RunMode,
		Conn:    conn,
	}, nil
}

func (c *Cmd) Close() error {
	return c.Conn.Close()
}

func (c *Cmd) Get(key string) (reply interface{}, err error) {
	return c.Conn.Do("GET", key)
}

func (c *Cmd) Set(key string, value interface{}) (reply interface{}, err error) {
	return c.Conn.Do("SET", key, value)
}

type JSONCmd struct {
	rejson.ReJSON
}

func (c *Cmd) JSON() *JSONCmd {

	rjh := rejson.NewReJSONHandler()
	rjh.SetRedigoClient(c.Conn)

	return &JSONCmd{rjh}
}
